package com.jiuyin.dianjing.ui.activity.setting;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.decoration.CustomDividerItemDecoration;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.PostModel;
import com.jiuyin.dianjing.model.ThumbModel;
import com.jiuyin.dianjing.ui.activity.base.BaseRefreshActivity;
import com.jiuyin.dianjing.ui.activity.community.PostDetailActivity;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COLLECT_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_POST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TARGETID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.OSS_IMG_SCREEN_TOPIC;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;

/**
 * 收藏
 */
public class SettingCollectionActivity extends BaseRefreshActivity<PostModel> {
    public SettingCollectionActivity() {
        super(PAGE_NUM);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_setting_my_collection;
    }

    @Override
    protected void initData() {
        mAdapter = new BaseRecyclerAdapter<PostModel>(R.layout.item_post) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, PostModel model, int position) {
                if (null != model) {
                    TextView tvComment = holder.itemView.findViewById(R.id.tv_comment);
                    TextView tvClicked = holder.itemView.findViewById(R.id.tv_clicked);
                    CheckedTextView tvThumb = holder.itemView.findViewById(R.id.tv_thumb);
                    holder.text(R.id.tv_name, model.getNickname());
                    holder.text(R.id.tv_time, model.getCreate_time());
                    holder.text(R.id.tv_title, model.getTitle());
                    holder.text(R.id.tv_content, model.getContent());
                    holder.text(R.id.tv_tag_desire, model.getGenre_tag());
                    holder.text(R.id.tv_tag_game, model.getGame_tag());
                    tvComment.setText(model.getComment_num());
                    tvClicked.setText(model.getClick_num());
                    tvThumb.setText(model.getThumb_num());
                    tvThumb.setChecked(model.getIsThumb() == 1);
                    ImageView ivHead = holder.itemView.findViewById(R.id.iv_head);
                    holder.itemView.findViewById(R.id.iv_more).setVisibility(View.GONE);
                    StringBuilder url = new StringBuilder(model.getHeader());
                    url.append(OSS_IMG_SCREEN_TOPIC);
                    Glide.with(getApplicationContext()).load(url.toString()).into(ivHead);
                    BGANinePhotoLayout ninePhotoLayout = holder.itemView.findViewById(R.id.layout_nine_grid);
                    ArrayList<String> photos = (ArrayList<String>) model.getPhoto();
                    if (photos != null) {
                        ArrayList<String> newPhotos = new ArrayList<>(photos.size());
                        for (String str : photos) {
                            StringBuilder sb = new StringBuilder(str);
                            sb.append(OSS_IMG_SCREEN_TOPIC);
                            newPhotos.add(sb.toString());
                        }
                        ninePhotoLayout.setDelegate(new BGANinePhotoLayout.Delegate() {
                            @Override
                            public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                                photoPreviewWrapper();
                            }

                            /**
                             * 图片预览
                             */
                            private void photoPreviewWrapper() {
                                BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder =
                                        new BGAPhotoPreviewActivity.IntentBuilder(getApplicationContext());
                                if (ninePhotoLayout.getItemCount() == 1) {
                                    // 预览单张图片
                                    photoPreviewIntentBuilder.previewPhoto(photos.get(ninePhotoLayout.getCurrentClickItemPosition()));
                                } else if (ninePhotoLayout.getItemCount() > 1) {
                                    // 预览多张图片
                                    photoPreviewIntentBuilder.previewPhotos(photos)
                                            .currentPosition(ninePhotoLayout.getCurrentClickItemPosition()); // 当前预览图片的索引
                                }
                                startActivity(photoPreviewIntentBuilder.build());
                            }

                            @Override
                            public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                                ninePhotoLayout.setIsExpand(true);
                                ninePhotoLayout.flushItems();
                            }
                        });
                        ninePhotoLayout.setData(newPhotos);
                    }
                    tvThumb.setOnClickListener(v -> {
                        ApiResultCallback apiResultCallback = new ApiResultCallback() {
                            @Override
                            public void onSuccess(JsonObject data) {
                                ThumbModel thumbModel = new Gson().fromJson(data, ThumbModel.class);
                                tvThumb.setChecked(thumbModel.isThumb == 1);
                                tvThumb.setText(thumbModel.thumb_num);
                                tvThumb.setEnabled(true);
                                model.setThumb_num(thumbModel.thumb_num);
                                model.setIsThumb(thumbModel.isThumb);
                            }

                            @Override
                            public void onFail(String msg) {
                                ToastUtil.showShort(msg);
                                tvThumb.setEnabled(true);
                            }

                            @Override
                            public void onError(String msg) {
                                tvThumb.setEnabled(true);
                                LogUtil.log(msg);
                            }
                        };
                        HashMap<String, Object> map = new HashMap<>();
                        map.put(KEY_TOKEN, HelperApplication.getToken());
                        map.put(KEY_TARGETID, model.getTopic_id());//评论或者 帖子主键
                        map.put(KEY_TYPE, tvThumb.isChecked() ? 0 : 1);//0 取消点赞 1 点赞
                        JSONObject json = new JSONObject(map);
                        tvThumb.setEnabled(false);
                        ServerApi.post(ApiEnum.APP_TOPIC_THUMB.getUrl(), json, null, progress, d -> addDisposable(d), apiResultCallback);
                    });
                }
            }
        };
        mAdapter.setOnItemClickListener((parent, view, position, id) -> {
            PostModel model = mAdapter.getItem(position);
            Bundle bundle = new Bundle();
            bundle.putSerializable(KEY_POST, model);
            goTargetActivity(PostDetailActivity.class, bundle);
        });

        mRcvPage.addItemDecoration(new CustomDividerItemDecoration(this));//添加分割线
        mRcvPage.setItemAnimator(new DefaultItemAnimator());
        mRcvPage.setAdapter(mAdapter);
        fetchData();
    }

    @Override
    protected void initView() {
        setTitle(R.string.my_collect);
    }

    @Override
    protected void fetchData() {
        HashMap<String, Object> data = new HashMap<>();
        data.put(KEY_TOKEN, HelperApplication.getToken());
        data.put(KEY_PAGE_NUM, mPageNum);
        JSONObject jsonObject = new JSONObject(data);
        ProgressDialogCallback progress = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ApiResultCallback request = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                if (null != data && data.has(KEY_COLLECT_LIST)) {
                    List<PostModel> postModels = new Gson().fromJson(data.getAsJsonArray(KEY_COLLECT_LIST), new TypeToken<List<PostModel>>() {
                    }.getType());
                    dealWithSuccessInfo(postModels);
                } else {
                    dealOtherInfo();
                }
            }

            @Override
            public void onFail(String msg) {
                LogUtil.log("SettingCollectionActivity onFail msg = " + msg);
                dealOtherInfo();
            }

            @Override
            public void onError(String msg) {
                LogUtil.log("SettingCollectionActivity onError msg = " + msg);
                dealOtherInfo();
            }
        };
        ServerApi.post(ApiEnum.APP_GET_USER_COLLECT_LIST_API.getUrl(), jsonObject, null,
                progress, d -> addDisposable(d), request);

    }

    public void refresh() {
        mPageNum = PAGE_FIRST;
        fetchData();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            refresh();
        }
    }
}
